<?php

namespace Admin\Frontend\Controllers;

use Admin\Models\read\Comment;
use function GuzzleHttp\Psr7\_caseless_remove;
use Helpers\User;
use Helpers\XhException;
use Modules\School;
use Phalcon\Di;
use Phalcon\Db\Column;
use Helpers\HttpClient;
use Helpers\Main;
use Helpers\UserPower;
use Helpers\Template;
use Helpers\Assets;
use Admin\Models\read\BaseRead;
use Admin\Models\read\Channel;
use Admin\Models\read\Article;
use Admin\Models\read\ArticleChannel;
use Admin\Models\read\ArticleStatistics;
use Admin\Models\read\User as ReadUser;
use Services\Read;

class ReadController extends ControllerBase
{

    const Key       = 'CA105003';       //文件服务器key

    private $stages = [1 => '小学', 2 => '初中', 3 => '高中'];    //学段
    private $channelEnum = [
        'iscomment' => [1 => '允许', 2 => '不允许']
    ];
    private $commentEnum = [
        'status'    => [0 => '未审核', 1 => '正常', 2 => '删除', 3 => '屏蔽', 4 => '审核未通过',5 =>'待审池']
    ];

    /**
     * 初始化时连接数据库
     *
     * create by ck 20170302
     */
    public function initialize()
    {
        error_reporting(E_ERROR);
        BaseRead::setReadDBService();
    }

    /**
     * 添加文章页面（两种文章）
     *
     * create by ck 20170307
     */
    public function articleAddAction()
    {
        $this->view->pick('read/articleAdd');
        $id = $this->request->getQuery('id', 'int');
        if ($id) {
            Main::showNavPosition('悦读管理', '编辑文章');
        } else {
            Main::showNavPosition();
        }
        if (!UserPower::checkUserPower($id ? 'Read_ArticleList_Edit' : 'Read_ArticleList_Add')) {
            return $this->sendViewError('无操作权限');
        }
//        Assets::UEditor('js/read/articleAdd.js');
        Assets::UMEditor('js/read/articleAdd.js');
        Assets::select2();
        Assets::importMainJs('assets/jquery/jquery.form.js');
        Assets::importMainJs('assets/jquery/ajaxfileupload.js');
        return $this->view->setVars([
//            'columnsArr' => Channel::getColumnsArray(),
            'columnsArr' => $this->getChannelList(['page' => 0, 'pageSize' => 5000], true),
//            'markerArr'  => Channel::getMarkerArray()
        ]);
    }

    /**
     * 获取栏目下连载内容
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170323
     * modify by ck 20170503    添加学段信息
     * modify by qgz 20181023 重构，使用接口
     */
    public function getChannelChildAction()
    {
        $fina[] = ['id' => '', 'text' => ''];
        $learnStages = '';
        $id = $this->request->getPost('id', 'int');
        $params = [
            'page' => 0,
            'pageSize' => 5000,
            'channelId' => $id
        ];
        try {
            $label = Read::getLabelList($params);//连载数据
            if ($label && isset($label['totalCount']) && $label['totalCount'] > 0 && $label['data']) {
                foreach ($label['data'] as $value) {
                    $fina[] = ['id' => $value['labelId'], 'text' => $value['labelName']];
                }
            }
            $data = $this->getChannelList($params);//栏目数据，获取学段信息
            if ($data && isset($data['totalCount']) && $data['totalCount'] > 0 && $data['data']) {
                foreach ($data['data'] as $datum) {
                    if ($datum['id'] == $id) {
                        $learnStages = $datum['learnstages'];
                    }
                }
            }
            return $this->sendJsonResponse(['marker' => $fina, 'stages' => $learnStages]);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
//
//        $this->view->disable();
//        $id = $this->request->getPost('id', 'int');
//        $channel = Channel::find([
//            'columns'    => 'id,channelname AS text',
//            'conditions' => 'status = 1 AND type = 2 AND parentid = :parentid:',
//            'order'      => 'sortnumber desc',
//            'bind'       => ['parentid' => $id],
//            'bindType'   => ['parentid' => Column::BIND_PARAM_INT]
//        ]);
//        $learnStages = Channel::findFirst($id)->learnstages;
//        if ($channel) {
//            $channel = array_merge([['id' => '', 'text' => '']], $channel->toArray());
//        } else {
//            $channel = [['id' => '', 'text' => '']];
//        }
//        return $this->response->setJsonContent(['marker' => $channel, 'stages' => $learnStages]);
    }

    /**
     * 根据id获取文章信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170331
     * modify by qgz 20181023 走接口
     */
    public function getArticleInfoAction()
    {
        $id = $this->request->getPost('id', 'int');
        try {
            $data = Read::getArticleData($id);
            $data['contents'] = base64_decode($data['contents']);
            $data['columns'] = $data['channelId'];
            $data['marker'] = $data['labelId'];
            $data['prerelease'] = $data['prerelease'] ?
                date('Y-m-d', $data['prerelease'] / 1000) : '';
            $data['articleStatus'] = $data['releasestatus'];//文章是否发布了
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
//        $this->view->disable();
//        $id = $this->request->getPost('id', 'int');
//        $article = Article::findFirst($id);
//        if (!$article) {
//            return $this->sendErrorResponse(400, '查无次文章！');
//        }
//        $article = $article->toArray();
//        $article['contents'] = base64_decode($article['contents']);
//
//        //组合栏目及连载
//        $channels = ArticleChannel::find([
//            'conditions' => 'articleid = :id: AND status = 1',
//            'bind'       => ['id' => $id],
//            'bindType'   => ['id' => Column::BIND_PARAM_INT]
//        ]);
//        foreach ($channels as $channel) {
//            if ($channel->type == 1) {
//                $article['columns'] = $channel->channelid;
//            } elseif ($channel->type == 2) {
//                $article['marker'] = $channel->channelid;
//            }
//        }
//        return $this->sendJsonResponse($article);
//        return $this->response->setJsonContent($article);
    }

    /**
     * 编辑文章内容
     *
     * create by ck 20170228
     * modify by ck 20170321    立即发布则url添加时间
     * modify by ck 20170412    编辑已发布文章不修改发布时间等信息
     * modify by ck 20170503    添加学段字段
     * modify by ck 20170509    发布后调用接口刷新Redis
     * modify by ck 20170519    刷新Redis接口结构更改
     * modify by ck 20170806    修复修改未发布文章时直接点击发布，导致发布时间未更改BUG
     */
    public function modifyArticleDataAction()
    {
        $this->view->disable();
        $data = $this->request->getPost();
        $data['learnstages'] = implode(',', $data['learnstages']);
        if (!$data['title']) {
            return $this->sendErrorResponse(400, '缺少标题！');
        }
        if (!$data['contents']) {
            return $this->sendErrorResponse(400, '文章内容不能为空！');
        }
        if (!$data['learnstages']) {
            return $this->sendErrorResponse(400, '学段不能为空！');
        }
        try {
            if ($data['id']) {//更新
                $params = [
                    'id' => $data['id'],
                    'articletype' => $data['articletype'],
                    'contents' => base64_encode($data['contents']),
                    'coverurl' => $data['coverurl'],
                    'learnstages' => $data['learnstages'],
                    'prerelease' => $data['prerelease'] ? strtotime($data['prerelease']) * 1000 : '',
                    'releasestatus' => $data['releasestatus'],
                    'title' => $data['title'],
                    'allowCommentDay' => $data['allowCommentDay'],
                    'updateuserid' => (int)User::getId()
                ];
                $channelArr = [];
                if ($data['columns']) {
                    $channelArr[] = ['channelid' => $data['columns'], 'type' => 1];
                }
                if ($data['marker']) {
                    $channelArr[] = ['channelid' => $data['marker'], 'type' => 2];
                }
                if ($channelArr) {
                    $params['channelArticleInputDTOS'] = $channelArr;
                }
                $articleUrl = $this->
                createHtmlFileAndUpload($data['title'], $data['contents'], $data['articletype'], $data['marker']);
                if (!is_string($articleUrl)) {
                    return $this->sendErrorResponse(500, $articleUrl['error']);
                }
                $params['articleurl'] = $articleUrl;
                Read::modifyArticle($params);
            } else {//新增接口
                if (!$data['columns']) {
                    return $this->sendErrorResponse(400, '栏目不能为空！');
                }
                $params = [
                    'articletype' => $data['articletype'],
                    'contents' => base64_encode($data['contents']),
                    'coverurl' => $data['coverurl'],
                    'createuserid' => User::getId(),
                    'learnstages' => $data['learnstages'],
                    'prerelease' => $data['prerelease'] ? strtotime($data['prerelease']) * 1000 : '',
                    'releasestatus' => $data['releasestatus'],
                    'title' => $data['title'],
                    'allowCommentDay' => $data['allowCommentDay']
                ];
                $channelArr = [];
                if ($data['columns']) {
                    $channelArr[] = ['channelid' => $data['columns'], 'type' => 1];
                }
                if ($data['marker']) {
                    $channelArr[] = ['channelid' => $data['marker'], 'type' => 2];
                }
                if ($channelArr) {
                    $params['channelArticleInputDTOS'] = $channelArr;
                }
                $articleUrl = $this->
                createHtmlFileAndUpload($data['title'], $data['contents'], $data['articletype'], $data['marker']);
                if (!is_string($articleUrl)) {
                    return $this->sendErrorResponse(500, $articleUrl['error']);
                }
                $params['articleurl'] = $articleUrl;
                Read::addArticle($params);
            }
            return $this->sendSuccessResponse('保存成功！');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '保存失败', $e->getMessage());
        }


//        try {
//            $result = $this->
//createHtmlFileAndUpload($data['title'], $data['contents'], $data['articletype'], $data['marker']);
//            if (!is_string($result)) {
//                return $this->sendErrorResponse(400, $result['error']);
//            }
//            $data['articleurl'] = $result;
//            $data['contents'] = base64_encode($data['contents']);
//            $data['releasestatus'] == 1 or $data['releasestatus'] = 2;
//            $article = Article::createRecord($data);
//            $article->prerelease or $article->prerelease = null;
//            $new = $article->id ? false : true;
//            if ($article->releasestatus == 1 && !$article->releasetime) {
//                $article->releasetime = date('Y-m-d H:i:s');
//                $article->articleurl .= '?d=' . date('m-d');
//            }
//            if (!UserPower::checkUserPower($new ? 'Read_ArticleList_Add' : 'Read_ArticleList_Edit')) {
//                return $this->sendErrorResponse(403, '无操作权限！');
//            }
//
//            //事务开始
//            $this->di->get(BaseRead::Service)->begin();
//            if (!$article->save()) {
//                return $this->sendErrorResponse(400, '文章保存失败！');
//            }
//            if (!ArticleChannel::createRecord($article->id, $data['columns'], 1)) {
//                $this->di->get(BaseRead::Service)->rollback();
//                return $this->sendErrorResponse(400, '栏目保存失败！');
//            }
//            if ($data['marker']) {
//                if (!ArticleChannel::createRecord($article->id, $data['marker'], 2)) {
//                    $this->di->get(BaseRead::Service)->rollback();
//                    return $this->sendErrorResponse(400, '标签保存失败！');
//                }
//            }
//            $this->di->get(BaseRead::Service)->commit();
//            //事务结束
////            Main::createCommitLog('read', 'Article', $new ? 'add' : 'edit', $data, $article->id);
//
            //如果直接发布，则调用接口刷新
//            if ($article->releasestatus == 1 && !$this->refreshChannel([$data['columns'] => $article->id], 1)) {
////                return $this->response->setContent('success:刷新缓存失败！请联系管理员！');
//                return $this->sendErrorResponse(400, '保存成功！刷新缓存失败，请联系管理员！');
//            }
//            return $this->response->setContent('success');
//            return $this->sendSuccessResponse('保存成功！');
//        } catch (\Exception $e) {
//            return $this->sendErrorResponse(500, '保存失败', $e->getMessage());
//        }
    }

    /**
     * 普通文章添加标题及连载名称
     *
     * @param $content
     * @param $title
     * @param $markerId
     * @return string
     * @throws \Exception
     *
     * create by ck 20170321
     * modify by ck 20170324    添加连载Id
     */
    private function dealNormalArticleContent($content, $title, $markerId)
    {
        $params = [
            'page' => 0,
            'pageSize' => 5000
        ];
        $markerName = '';
        $data = Read::getLabelList($params);
        if ($data && isset($data['totalCount']) && $data['totalCount'] > 0 && $data['data'] && $markerId) {
            foreach ($data['data'] as $datum) {
                if ($datum['labelId'] == $markerId) {
                    $markerName = $datum['labelName'];
                }
            }
        }
//        $markerName = $markerId ? Channel::getMarkerArray()[$markerId] : '';
        $date = date('m-d');
        return
"<div class='title-div'>
    <h2 id='article_title'>{$title}</h2>
    <span id='article_explain'>
        <span id='article_date'>{$date}</span>
        <span id='article_channel'>{$markerName}</span>
        <span id='article_channelId'>{$markerId}</span>
    </span>
    <hr />
</div>" . $content;
    }

    /**
     * 检查图文文章格式是否正确并生成html内容
     *
     * @param $content
     * @return array|string
     * @throws \Exception
     * create by ck 20170307
     */
    private function dealTeletextArticleContent($content)
    {
        require_once(APP_PATH . "/helpers/simple_html_dom.php");
        $sourceHtml = str_get_html($content);
        $needImg = true;
        $line = 1;
        $imgArr = $explainArr = $divArr = [];
        foreach ($sourceHtml->find('p') as $p) {
            if ($needImg) {
                if (!$p->find('img', 0)) {
                    throw new \Exception("文章第{$line}行缺少图片");
//                    return $this->sendErrorResponse(400, "文章第{$line}行缺少图片");
                }
                if ($p->plaintext) {
                    throw new \Exception("文章第{$line}行不应出现文字");
//                    return $this->sendErrorResponse(400, "文章第{$line}行不应出现文字");
                }
                $imgArr[] = $p->find('img', 0)->getAttribute('src');
            } else {
                if (!$p->plaintext) {
                    throw new \Exception("文章第{$line}行缺少文字");
//                    return $this->sendErrorResponse(400, "文章第{$line}行缺少文字");
                }
                $explainArr[] = $p->plaintext;
            }
            $needImg = !$needImg;
            $line++;
        }
        foreach ($imgArr as $index => $src) {
            $divArr[] =
"<div class='item'>
    <div class='box'>
        <img src='{$src}' data='{$explainArr[$index]}'>
    </div>
    <div class='carousel-caption'>
        <span class='page'></span>/<span></span>
        <span></span>
    </div>
</div>";
        }
        $sourceHtml->clear();
        unset($sourceHtml);
        $content =
'<div class="carousel slide" id="teletext">
    <div class="carousel-header">
    </div>
    <div class="carousel-inner">
        ' . implode('', $divArr) . '
    </div>
    <a class="carousel-control left" data-slide="prev" href="#teletext">
        <span class="glyphicon "></span>
    </a>
    <a class="carousel-control right" data-slide="next" href="#teletext">
        <span class="glyphicon "></span>
    </a>
</div>';
        return $content;
    }

    /**
     * 根据标题及内容生成html文件并上传文件服务器返回url
     *
     * @param $title            --标题
     * @param $content          --内容
     * @param int $type         --类型(1=普通，2=图文)
     * @param null $markerId    --连载ID
     * @return array|bool|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Exception
     * create by ck 20170228
     * modify by ck 20170305
     * modify by ck 20170306    公式解析文件从配置读取
     * modify by ck 20170310    引入改变字体大小js
     * modify by ck 20170321    普通文章引入相应样式
     */
    private function createHtmlFileAndUpload($title, $content, $type = 1, $markerId = null)
    {
        $filePath = Main::getConfigByName('appParse');
        $filePath = isset($filePath['tempPath']) ? $filePath['tempPath'] : '/Mailserver/cache/temp/';
        $includeRes = '';

        //引入调整字体文件
        $readRes = Main::getConfigByName('readRes');
        $resList = json_decode($readRes['fontsize'], true);

        //如包含公式则引入相应解析样式及脚本
        if (strpos($content, 'mathquill-embedded-latex') !== false) {
            $resList = array_merge($resList, json_decode($readRes['mathquill'], true));
        }

        //根据类型引入相应样式并处理
        if ($type == 1) {
            $resList = array_merge($resList, json_decode($readRes['normal'], true));
            $content = $this->dealNormalArticleContent($content, $title, $markerId);
        } elseif ($type == 2) {
            $resList = array_merge($resList, json_decode($readRes['teletext'], true));
            $content = $this->dealTeletextArticleContent($content);
            if (is_array($content)) {
                return $content;
            }
        }

        //组合引入的资源文件
        foreach ($resList as $res) {
            $resType = pathinfo($res, PATHINFO_EXTENSION);
            if ($resType == 'js') {
                $includeRes .= "<script src='{$res}'></script>";
            } elseif ($resType == 'css') {
                $includeRes .= "<link rel='stylesheet' href='{$res}'>";
            }
        }

        //生成html文件并上传文件服务器
        $html =<<<ARTICLE
<!DOCTYPE html>
<html lang='en'>
<head>
	<meta charset='UTF-8'>
	<meta name='format-detection' content='telephone=no'>
	<meta name='viewport' content='width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no'>
	<title>{$title}</title>
	{$includeRes}
</head>
<body>
	{$content}
</body>
</html>
ARTICLE;
        $fileName = $filePath . md5($title) . '.html';
        if (!file_put_contents($fileName, $html)) {
            return $this->sendErrorResponse(400, '文件写入失败!');
        }
        $result = Main::uploadToFileManageSystem($fileName, 'html', self::Key, true);

        @unlink($fileName);
        if (!$result) {
            return $this->sendErrorResponse(400, '文件上传失败!');
        }
        return $result;
    }

    /**
     * 上传图片到文件服务器并返回url
     *
     * create by ck 20170228
     * modify by ck 20170305    更改为UEditor格式
     */
    public function uploadArticleImageAction()
    {
        $this->view->disable();
        if ($this->request->hasFiles()) {
            $type = $this->request->getQuery('editorid');
            $file = $this->request->getUploadedFiles()[0];
            $filePath = Main::getConfigByName('appParse');
            $filePath = isset($filePath['tempPath']) ? $filePath['tempPath'] : '/Mailserver/cache/temp/';
            $fileName = $file->getName();
            if ($file->getSize() > 200 * 1024) {
                if ($type == 'contents') {
                    return $this->sendJsonResponse(['state' => '文件大小不可超过200K！']);
                } else {
                    return $this->sendErrorResponse(400, '文件大小不可超过200K，请重新选择！');
                }
            }
            $fullPath = $filePath . $fileName;
            if (!is_writable($filePath)) {
                return $this->sendErrorResponse(403, $filePath . '缓存无写入权限！');
            }
            $file->moveTo($fullPath);
            $result = Main::uploadToFileManageSystem($fullPath, 'img', self::Key, true);
            @unlink($fullPath);
            if (!$result) {
                return $this->sendErrorResponse(400, '上传失败！');
            }
            return $this->response->setJsonContent([
                'name'          => basename($result),
                'originalName'  => $fileName,
                'size'          => $file->getSize(),
                'state'         => 'SUCCESS',
                'type'          => $file->getExtension(),
                'url'           => $result
            ]);//->setContentType('text/html');//->send();
        }
    }

    /**
     * 获取栏目列表
     *
     * @param array $params
     * @param bool $enum
     *
     * @return array|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by qgz 20181022
     */
    public function getChannelList($params = [], $enum = false)
    {
        try {
            $data = Read::getChannelList($params);
            $return = [];
            if ($enum && isset($data['totalCount']) && $data['totalCount'] > 0 && isset($data['data'])) {
                foreach ($data['data'] as $datum) {
                    $return[$datum['id']] = $datum['channelname'];
                }
            } else {
                $return = $data;
            }
            return $return;
        } catch (\Exception $e) {
            throw $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 文章列表页面
     *
     * create by ck 20170301
     * modify by ck 20170613    添加栏目/文章筛选控件
     * modify by qgz 20181022 重构，数据走接口
     */
    public function articleManageListAction()
    {
        $this->view->pick('read/articleManageList');
        Main::showNavPosition();
        Assets::easyUI('js/read/articleManageList.js');
        if (!UserPower::checkUserPower('Read_ArticleList')) {
            return $this->sendViewError('对不起，您没有查看此页面的权限');
        }
        if (!Template::exists('Read_Article', 'list')) {
            return $this->sendViewError('配置文件不存在，请先创建！');
        }
        $listSearchArr = $listButtonArr = [];
        if (UserPower::checkUserPower('Read_ArticleList_Edit')) {
            $listButtonArr[] = ['id' => 'bt_list_publish', 'text' => '发布', 'plain' => 'true',
                                'icon' => 'fa-mail-forward'];
        }
        if (UserPower::checkUserPower('Read_ArticleList_Del')) {
            $listButtonArr[] = ['id' => 'bt_list_del', 'text' => '删除', 'plain' => 'true', 'icon' => 'fa-trash'];
        }
        if (UserPower::checkUserPower('Read_ArticleList_DelComment')) {
            $listButtonArr[] = ['id' => 'bt_list_del_comment', 'text' => '删除评论', 'plain' => 'true',
                                'icon' => 'fa-trash'];
        }
        $listSearchArr[] = ['type' => 'select', 'id' => 'List_Search_Channel', 'style' => 'width:120px;',
//                            'data' => ['' => '--选择栏目--'] + Channel::getColumnsArray()];
                            'data' => ['' => '--选择栏目--'] + $this->getChannelList([
                                    'page' => 0, 'pageSize' => 5000], true)
        ];

        $listSearchArr[] = ['type' => 'text', 'class' => 'easyui-datebox', 'id' => 'list_start', 'label' => ' 开始日期：'];
        $listSearchArr[] = ['type' => 'text', 'class' => 'easyui-datebox', 'id' => 'list_end', 'label' => ' 截止日期：'];
        $listSearchArr[] = ['type' => 'text', 'id' => 'List_Search_Article', 'label' => ' 文章：'];
        return $this->view->setVars([
            'List'          => Template::createList('List', 'Read_Article', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ]);
    }

    /**
     * 获取文章列表信息
     *
     * create by ck 20170301
     * modify by ck 20170503    添加学段字段
     * modify by ck 20170612    添加文章统计信息及排序功能
     * modify by ck 20170613    添加栏目/文章标题筛选
     * modify by qgz 20181022 重构，数据走接口
     */
    public function getArticleListAction()
    {
        $channelId = $this->request->getPost('channelId', 'int');//栏目
        $articleTitle = $this->request->getPost('articleTitle', 'string');//文章
        $startDate = $this->request->getPost('startDate', 'string');
        $endDate = $this->request->getPost('endDate', 'string');
        $sort = $this->request->get('sort', 'string');
        $order = $this->request->get('order', 'string', 'asc');
        $page = $this->request->getPost('page', 'int', 1);
        $rows = $this->request->getPost('rows', 'int', 0);
        $params = [
            'page' => $page - 1,
            'pageSize' => $rows
        ];
        $keyStrArr = ['read_count' => 'readCount', 'comment_count' => 'commentCount', 'share_count' => 'shareCount',
                      'collect_count' => 'collectCount', 'marker' => 'labelname'];
        if ($channelId) {
            $params['channelId'] = $channelId;
        }
        if ($articleTitle) {
            $params['title'] = $articleTitle;
        }
        if ($sort) {
            if (isset($keyStrArr[$sort]) || in_array($sort, ['releasetime', 'createtime'])) {
                $params['sort'] = $keyStrArr[$sort];
            } else {
                return $this->sendErrorResponse(400, '没有该排序字段参数');
            }
            $params['direction'] = $order;
        }
        if ($startDate) {
            $params['startTime'] = strtotime($startDate) * 1000;
        }
        if ($endDate) {
            $endDate .= ' 23:59:59';
            $params['endTime'] = strtotime($endDate) * 1000;
        }
        try {
            $data = Read::getArticleList($params);
            $return = ['rows' => [], 'total' => 0];
            if ($data && isset($data['totalCount']) && $data['totalCount'] != 0 && $data['data']) {
                $return['total'] = $data['totalCount'];
                foreach ($data['data'] as $datum) {
                    foreach ($keyStrArr as $key => $value) {
                        $datum[$key] = $datum[$value];
                    }
                    $datum['columns'] = $datum['channelname'];
                    $datum['articletype'] = $datum['articletype'] == 1 ? '普通' : '图文';
                    $datum['releasestatus'] = $datum['releasestatus'] == 1 ? '已发布' : '未发布';
                    $datum['articleurl'] = $datum['articleurl'] ?
                        "<a href='{$datum['articleurl']}' target='_blank'>点击预览</a>" : '';
                    $datum['coverurl'] = $datum['coverurl'] ?
                        "<a href='{$datum['coverurl']}' target='_blank'>点击查看</a>" : '';
                    $datum['releasetime'] = $datum['releasetime'] ?
                        date('Y-m-d H:i:s', $datum['releasetime'] / 1000) : '';
                    $datum['createtime'] = $datum['createtime'] ?
                        date('Y-m-d H:i:s', $datum['createtime'] / 1000) : '';
                    $datum['prerelease'] = $datum['prerelease'] ?
                        date('Y-m-d H:i:s', $datum['prerelease'] / 1000) : '';
                    $return['rows'][] = $datum;
                }
            }
            $this->dealLearnStages($return['rows'], 'learnstages');
            return $this->sendJsonResponse($return);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }

//        $this->view->disable();
//
//        //获取文章信息，无信息则直接输出
////        $parameters = [
////            'columns'    => ['id', 'title', 'articletype', 'releasestatus', 'learnstages', 'articleurl', 'coverurl', 'releasetime', 'createtime'],
////            'conditions' => 'status = 1',
////            'order'      => 'id desc'
////        ];
////        $data = Main::runModelPaginator('\\Admin\\Models\\read\\Article', $parameters, true);
////        $data['total'] > 0 or die(json_encode($data));
//        $articleQuery = $this->modelsManager->createBuilder()
//            ->columns(['A.id', 'A.title', 'A.articletype', 'A.releasestatus', 'A.learnstages', 'A.articleurl', 'A.coverurl',
//                'A.releasetime', 'A.createtime', 'A.prerelease', 'B.read_count', 'B.comment_count', 'B.share_count', 'B.collect_count'])
//            ->from(['A' => '\\Admin\\Models\\read\\Article'])
////            ->leftJoin('\\Admin\\Models\\read\\ArticleChannel', 'A.id = C.articleid', 'C')
//            ->leftJoin('\\Admin\\Models\\read\\ArticleStatistics', 'A.id = B.article_id', 'B')
//            ->where('A.status = 1')
//            ->orderBy("A.id desc");
//
//        $channelId    = $this->request->getPost('channelId', 'int');
//        $articleTitle = $this->request->getPost('articleTitle', 'string');
//        $startDate    = $this->request->getPost('startDate', 'string');
//        $endDate      = $this->request->getPost('endDate', 'string');
//        if ($channelId) {
//            $articleQuery->leftJoin('\\Admin\\Models\\read\\ArticleChannel', 'A.id = C.articleid AND C.status = 1', 'C')
//                ->andWhere('C.channelid = ?1', [1 => $channelId]);
//        }
//        if ($articleTitle) {
//            $articleQuery->andWhere("A.title like '%{$articleTitle}%'");
//        }
//        if ($startDate) {
//            $articleQuery->andWhere("A.releasetime >= ?2", [2 => $startDate]);
//        }
//        if ($endDate) {
//            $endDate .= ' 23:59:59';
//            $articleQuery->andWhere('A.releasetime <= ?3', [3 => $endDate]);
//        }
//
//        //处理排序
//        $sort  = $this->request->get('sort', 'string');
//        $order = $this->request->get('order', 'string', 'asc');
//        if ($sort) {
//            if (property_exists(new ArticleStatistics(), $sort)) {
//                $articleQuery->orderBy("B.{$sort} {$order}");
//            } elseif (property_exists(new Article(), $sort)) {
//                $articleQuery->orderBy("A.{$sort} {$order}");
//            }
//        }
//
//        $data = Main::runBuilderPaginator($articleQuery, true);
//        if ($data['total'] <= 0) {
//            return $this->sendErrorResponse(400, json_encode($data));
//        }
////        $data['total'] > 0 or die(json_encode($data));
//
//        //获取文章ID及对应栏目/标签ID
//        $articleIds = array_column($data['rows'], 'id');
//        $channels = ArticleChannel::find([
//            'conditions' => 'status = 1 AND articleid IN ({articleId:array})',
//            'bind'       => ['articleId' => $articleIds]
//        ]);
//        $channelArr = [];
//        $columnsArr = Channel::getColumnsArray();
//        $markerArr  = Channel::getMarkerArray();
//        foreach ($channels as $channel) {
//            $channelArr[$channel->articleid][] = $channel->channelid;
//        }
//
//        //替换文章类型文字并添加栏目/标签
//        foreach ($data['rows'] as $index => $row) {
//            $data['rows'][$index]['articletype']   = $row['articletype'] == 1 ? '普通' : '图文';
//            $data['rows'][$index]['releasestatus'] = $row['releasestatus'] == 1 ? '已发布' : '未发布';
//            $data['rows'][$index]['articleurl']    = "<a href='{$row['articleurl']}' target='_blank'>点击预览</a>";
//            $data['rows'][$index]['coverurl']      = "<a href='{$row['coverurl']}' target='_blank'>点击查看</a>";
//            $columnsName = $markerName = [];
//            foreach ($channelArr[$row['id']] as $channelId) {
//                isset($columnsArr[$channelId]) and $columnsName[] = $columnsArr[$channelId];
//                isset($markerArr[$channelId])  and $markerName[]  = $markerArr[$channelId];
//            }
//            $data['rows'][$index]['columns'] = implode(',', $columnsName);
//            $data['rows'][$index]['marker'] = implode(',', $markerName);
//        }
//        $this->dealLearnStages($data['rows'], 'learnstages');
//        $this->response->setJsonContent($data)->send();
    }

    /**
     * 根据ID发布文章
     *
     * @param bool $autoPublish
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170311
     * modify by ck 20170321    发布时url中添加d参数
     * modify by ck 20170509    发布后调用接口刷新Redis
     * modify by ck 20170519    刷新Redis接口结构更改
     * modify by ck 20170602    刷新Redis时不判断是否已发布
     */
    public function publishArticleAction($autoPublish = false)
    {
        if (!$autoPublish) {
            if (!UserPower::checkUserPower('Read_ArticleList_Edit')) {
                return $this->sendErrorResponse(403, '无操作权限！');
            }
        }
        $ids = $this->request->getPost('ids', 'string');
        if (!$ids) {
            return $this->sendErrorResponse(400, '未选中文章!');
        }
        try {
            $params = [
                'updateUserId' => User::getId(),
                'actionType' => 1,
                'articleIds' => explode(',', $ids)
            ];
            Read::delArticle($params);
            return $this->sendSuccessResponse('成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '失败', $e->getMessage());
        }

//        $this->view->disable();
//        if (!$autoPublish) {
//            if (!UserPower::checkUserPower('Read_ArticleList_Edit')) {
//                return $this->sendErrorResponse(403, '无操作权限！');
//            }
//        }
//        $ids = $this->request->getPost('ids', 'string');
//        if (!$ids) {
//            return $this->sendErrorResponse(400, '未选中文章!');
//        }
//        //查找未发布文章id
////        $needPubId = Article::query()
////            ->columns('id')
////            ->where('releasestatus = 2')
////            ->andWhere("id in ({$ids})")
////            ->execute();
////        $needPubId  = $needPubId->toArray();
////        $needPubId  or die('无未发布文章！');
////        $needPubId  = array_column($needPubId, 'id');
////        $needPubIds = implode(',', $needPubId);
//        $needPubIds = $ids;
//
//        $nowTime   = date('Y-m-d H:i:s');
//        $nowDate   = date('m-d');
//        $updateSql = "update \\Admin\\Models\\read\\Article set releasestatus = 1, articleurl = concat(articleurl, '?d={$nowDate}'), releasetime = '{$nowTime}' where id in ({$needPubIds}) and releasestatus = 2";
//        $result    = $this->modelsManager->executeQuery($updateSql);
//        $result and Main::createCommitLog('read', 'Article', 'publish', ['ids' => $ids], null, '批量发布');
//
//        //获取栏目及对应文章id并刷新接口
//        if ($result) {
//            $data = ArticleChannel::find([
//                'columns'    => 'channelid,group_concat(articleid) as articleids',
//                'conditions' => "status = 1 AND type = 1 AND articleid IN ({$needPubIds})",
//                'group'      => 'channelid'
//            ]);
//            if ($data) {
//                $data = $data->toArray();
//                $data = array_column($data, 'articleids', 'channelid');
////                $data = array_column($data, 'channelid');
////                $data = array_unique($data);
////                $data = implode(',', $data);
//                if ($data && !$this->refreshChannel($data, 1)) {
////                    return $this->sendErrorResponse(400, '发布成功！缓存刷新失败，请联系管理员！');
//                    return $this->response->setContent('发布成功！缓存刷新失败，请联系管理员！');
//                }
//            }
//            return $this->sendSuccessResponse('发布成功！');
//        }
//        return $this->sendErrorResponse(400, '发布失败！');
//        return $this->response->setContent($result ? '发布成功！' : '发布失败！');
    }

    /**
     * 文章删除
     *
     * create by ck 20170305
     * modify by ck 20170311    删除文章时同时删除附属记录
     * modify by ck 20170620    删除后调用刷新接口
     * modify by ck 20180801    部分表改为物理删除
     */
    public function delArticleDataAction()
    {
        if (!UserPower::checkUserPower('Read_ArticleList_Del')) {
            return $this->sendErrorResponse(403, '无操作权限！');
        }
        $ids = $this->request->getPost('ids', 'string');
        if (!$ids) {
            return $this->sendErrorResponse(400, '未选中文章！');
        }
        try {
            $params = [
                'updateUserId' => User::getId(),
                'actionType' => 2,
                'articleIds' => explode(',', $ids)
            ];
            Read::delArticle($params);
            return $this->sendSuccessResponse('成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '失败', $e->getMessage());
        }


//        $this->view->disable();
//        if (!UserPower::checkUserPower('Read_ArticleList_Del')) {
//            return $this->sendErrorResponse(403, '无操作权限！');
//        }
//        $ids = $this->request->getPost('ids', 'string');
//        if (!$ids) {
//            return $this->sendErrorResponse(400, '未选中文章！');
//        }
//
//        try {
//            //事务开始
//            $this->di->get(BaseRead::Service)->begin();
//            $result = Article::deleteRecordById($ids);
//            if (!$result) {
//                return $this->sendErrorResponse(400, '删除失败！');
//            }
//            //处理评论等
//            $prefix = BaseRead::Prefix;
//            $tableArr = ['user_readarticle', 'article_channel', 'acknowledge', 'comment', 'collect', 'share'];
//            foreach ($tableArr as $tableName) {
//                if ($tableName == 'collect') {
//                    $sql = "delete from {$prefix}{$tableName} where articleid in ({$ids})";
//                } else {
//                    $sql = "update {$prefix}{$tableName} set status = 2 where articleid in ({$ids})";
//                }
//                if (!$this->di->getShared(BaseRead::Service)->execute($sql)) {
//                    $result = false;
//                    $this->di->get(BaseRead::Service)->rollback();
//                    break;
//                }
//            }
//            if (!$result) {
//                return $this->sendErrorResponse(400, '删除失败！');
//            }
//            $this->di->get(BaseRead::Service)->commit();
//            //事务结束
//            Main::createCommitLog('read', 'Article', 'del', ['ids' => $ids], null, '批量删除');
//
//            $data = ArticleChannel::find([
//                'columns'    => 'channelid,group_concat(articleid) as articleids',
//                'conditions' => "type = 1 AND articleid IN ({$ids})",
//                'group'      => 'channelid'
//            ]);
//            if ($data) {
//                $data = $data->toArray();
//                $data = array_column($data, 'articleids', 'channelid');
//                if ($data && !$this->refreshChannel($data, 2)) {
//                    return $this->response->setContent('删除成功！缓存刷新失败，请联系管理员！');
//                }
//            }
//            return $this->sendSuccessResponse('删除成功！');
//        } catch (\Exception $e) {
//            $this->di->get(BaseRead::Service)->rollback();
//            return $this->sendErrorResponse(500, '删除失败！' . $e->getMessage());
//        }
    }

    /**
     * 栏目/标签管理页面
     *
     * create by ck 20170227
     * modify by ck 20170407    权限更改
     * modify by ck 20180510
     */
    public function channelManageListAction()
    {
        $this->view->pick('read/channelManageList');
        Main::showNavPosition();
        Assets::easyUI('js/read/channelManageList.js');
        $type = $this->request->getQuery('type', 'int');
        if (!$type) {
            return $this->sendViewError('缺少类型参数');
        }
        $powerTag = $type == 1 ? 'Read_ColumnList' : 'Read_MarkerList';
        if (!UserPower::checkUserPower($powerTag)) {
            return $this->sendViewError('无页面查看权限');
        }
        Template::exists($type == 1 ? 'Read_Columns' : 'Read_Marker', 'both') or
        die(Main::showMessageModal('配置文件不存在，请先创建！'));
        $listButtonArr = $formButtonArr = [];
        if (UserPower::checkUserPower($powerTag . '_Add')) {
            $listButtonArr[] = array('id' => 'bt_list_add', 'text' => '增加', 'plain' => 'true', 'icon' => 'fa-plus');
            $formButtonArr[] = array('id' => 'bt_form_add', 'text' => '增加', 'class' => 'disabled');
            $this->view->setVar('AddEdit', true);
        }
        if (UserPower::checkUserPower($powerTag . '_Edit')) {
            $formButtonArr[] = array('id' => 'bt_form_edit', 'text' => '修改', 'class' => 'disabled');
            $this->view->setVar('AddEdit', true);
        }
        if (UserPower::checkUserPower($powerTag . '_Del')) {
            $listButtonArr[] = array('id' => 'bt_list_del', 'text' => '删除', 'plain' => 'true', 'icon' => 'fa-trash');
        }
        $formButtonArr[] = array('id' => 'bt_form_back', 'text' => '返回');
        $formButtonArr[] = array('id' => 'bt_form_reset', 'text' => '重置');
        $this->view->setVars(array(
            'type'          => $type,
            'List'          => Template::createList('List', $type == 1 ? 'Read_Columns' : 'Read_Marker', [
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ]),
            'Form'          => Template::createForm(
                $type == 1 ? 'Read_Columns' : 'Read_Marker',
                $type == 1 ? $this->channelEnum :
                    ['parentid' => $this->getChannelList(['page' => 0, 'pageSize' => 5000], true)]
            ),
            'FormButton'    => Template::createButtonToolBar($formButtonArr)
        ));
    }

    /**
     * 获取栏目/标签数据
     *
     * create by ck 20170227
     * modify by ck 20170322    连载添加所属栏目名称
     * modify by ck 20180510
     * modify by qgz 20181022 重构 数据走接口
     */
    public function getChannelListAction()
    {
        $type = $this->request->getQuery('type', 'int');
        $page = $this->request->getPost('page', 'int', 1);
        $rows = $this->request->getPost('rows', 'int', 0);
        $params = [
            'page' => $page - 1,
            'pageSize' => $rows
        ];
        $return = ['rows' => [], 'total' => 0];
        try {
            if ($type == 1) {//栏目
                $data = $this->getChannelList($params);
                if ($data && isset($data['totalCount']) && $data['totalCount'] > 0 && $data['data']) {
                    $return['total'] = $data['totalCount'];
                    foreach ($data['data'] as $datum) {
                        $datum['iscommentcode'] = $datum['iscomment'];
                        $datum['iscomment'] = $this->channelEnum['iscomment'][$datum['iscomment']];
                        $datum['createtime'] = $datum['createtime'] ?
                            date('Y-m-d H:i:s', $datum['createtime'] / 1000) : '';
                        $datum['learnstagescode'] = $datum['learnstages'];
                        $return['rows'][] = $datum;
                    }
                    $this->dealLearnStages($return['rows'], 'learnstages');
                }
            } elseif ($type == 2) {//连载
                $data = Read::getLabelList($params);
                if ($data && isset($data['totalCount']) && $data['totalCount'] > 0 && $data['data']) {
                    $return['total'] = $data['totalCount'];
                    foreach ($data['data'] as $datum) {
                        $datum['parentidcode'] = $datum['id'];//所属栏目id
                        $datum['parentid'] = $datum['channelname'];//所属栏目名
                        $datum['id'] = $datum['labelId'];//连载id
                        $datum['channelname'] = $datum['labelName'];//连载名
                        $datum['createtime'] = $datum['createtime'] ?
                            date('Y-m-d H:i:s', $datum['createtime'] / 1000) : '';
                        $return['rows'][] = $datum;
                    }
                }
            } else {
                return $this->sendErrorResponse(400, '参数type类型不正确');
            }
            return $this->sendJsonResponse($return);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }

//        $this->view->disable();
//        $type = $this->request->getQuery('type', 'int');
//        $type or die('缺少类型参数！');
//        $columns = ['id', 'channelname', 'sortnumber', 'createtime'];
//        if($type == 1){
//            $columns = array_merge($columns, ['iscomment', 'learnstages', /*'publishnum', 'frequency', 'publishtime'*/]);
//        }
//        elseif($type == 2){
//            $columns = array_merge($columns, ['parentid']);
//        }
//        $parameters = [
//            'columns'    => $columns,
//            'conditions' => 'type = :type: AND status = 1',
//            'bind'       => ['type' => $type],
//            'order'      => 'sortnumber'
//        ];
//        $result = Main::runModelPage('\\Admin\\Models\\read\\Channel', $parameters, $this->channelEnum);
//        if($type == 2){
//            $columnsArr = Channel::getColumnsArray();
//            foreach($result['rows'] as $index => $row) {
//                $result['rows'][$index]['parentid'] = $columnsArr[$row['parentid']] ? $columnsArr[$row['parentid']] : '未知';
//            }
//        }
//        else{
//            $this->dealLearnStages($result['rows'], 'learnstages');
//        }
//        return $this->response->setJsonContent($result);
    }

    /**
     * 更改栏目/标签
     *
     * create by ck 20170227
     * modify by ck 20170407    权限更改
     * modify by ck 20170503    添加学段字段
     * modify by ck 20170619    刷新悦读栏目缓存
     */
    public function modifyChannelDataAction()
    {
        $type = $this->request->getQuery('type', 'int');
        $postData = $this->request->getPost();
        $powerTag = $type == 1 ? 'Read_ColumnList' : 'Read_MarkerList';
        UserPower::checkUserPower($postData['id'] ? $powerTag . '_Edit' : $powerTag . '_Add') or die('无操作权限！');
        $params = [
            'channelName' => $postData['channelname'],
            'sortNumber' => $postData['sortnumber'],
            'type' => $type,
            'userId' => User::getId()
        ];
        $updateParams = [
            'channelId' => $postData['id'],
            'userId' => User::getId(),
            'sortnumber' => $postData['sortnumber']
        ];
        if ($type == 1) {//栏目
            $params['isComment'] = $postData['iscomment'];
            $params['learnstages'] = $updateParams['learnstages'] =
                isset($postData['learnstages']) && $postData['learnstages'] ?
                implode(',', $postData['learnstages']) : '';
            $updateParams['iscomment'] = $postData['iscomment'];
        } else {//连载
            $params['parentId'] = $postData['parentid'];
        }
        try {
            if (!$postData['id']) {//创建
                Read::addChannelOrLabel($params);
            } else {//更新
                Read::modifyChannelOrLabel($updateParams);
            }
            return $this->sendSuccessResponse('成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }

//        $this->view->disable();
//        $type = $this->request->getQuery('type', 'int');
//        $type or die('缺少类型参数！');
//        $realData = Main::getRealData($this->request->getPost());
//        $realData['learnstages'] = implode(',', $realData['learnstages']);
//        $powerTag = $type == 1 ? 'Read_ColumnList' : 'Read_MarkerList';
//        $realData['type'] = $type;
//        $channel = Channel::createRecord($realData);
//        $new = $channel->id ? false : true;
//        UserPower::checkUserPower($new ? $powerTag . '_Add' : $powerTag . '_Edit') or die('无操作权限！');
//        $channel->save() or die(Main::showMessageModal(($new ? '新增' : '修改') . '失败'));
//        Channel::delCache();
//        if($type == 1){
//            Read::refreshChannel();
////            $this->refreshChannel();
//        }
//        Main::createCommitLog('read', 'Channel', $new ? 'add' : 'edit', $channel, $channel->id);
    }

    /**
     * 根据ID批量删除栏目/标签
     *
     * create by ck 20170228
     * modify by ck 20170407    权限更改
     * modify by ck 20170619    刷新悦读栏目缓存
     */
    public function delChannelDataAction()
    {
        $ids = $this->request->getPost('ids', 'string');
        if (!$ids) {
            return '请选择后操作';
        }
        $ids = explode(',', $ids);
        try {
            Read::delChannelOrLabel(User::getId(), $ids);
            return '成功';
        } catch (\Exception $e) {
            return $e->getMessage();
        }
//        $this->view->disable();
//        $ids = $this->request->getPost('ids', 'string');
//        (UserPower::checkUserPower('Read_ColumnList_Del') ||  UserPower::checkUserPower('Read_MarkerList_Del')) or die('无操作权限！');
//        $result = Channel::deleteRecordById($ids);
//        $this->response->setContent($result ? '删除成功！' : '删除失败！')->send();
//        Read::refreshChannel();
////        $this->refreshChannel();
//        Main::createCommitLog('read', 'Channel', 'del', ['ids' => $ids], null, '批量删除');
    }

    /**
     * 评论管理页面
     *
     * create by ck 20170420
     * modify by ck 20170601    添加恢复功能
     * modify by ck 20180531    添加时间筛选
     */
    public function commentManageListAction()
    {
        $this->view->pick('read/commentManageList');
        Main::showNavPosition();
        Assets::layUI();
        Assets::easyUI('js/read/commentManageList.js');
        if (!UserPower::checkUserPower('Read_Comment')) {
            return $this->sendViewError('无页面查看权限');
        }
        $listButtonArr = $listSearchArr = [];
        $listSearchArr[] = ['type'=>'select', 'id'=>'list_status', 'data'=> ['' => '全部评论', 0 => '未审核', 1 => '正常', 3 => '已屏蔽', 4 => '审核未通过', 5=>'待审池']];
        $listSearchArr[] = ['type'=>'text', 'class'=>'easyui-datetimebox', 'id'=>'list_start', 'label'=>' 时间：'];
        $listSearchArr[] = ['type'=>'text', 'class'=>'easyui-datetimebox', 'id'=>'list_end', 'label'=>' ~ '];
        $listSearchArr[] = ['type'=>'text', 'id'=>'list_vague', 'label'=>' 搜索： '];
        if (UserPower::checkUserPower('Read_Comment_Edit')) {
            $listButtonArr[] = ['id'=>'bt_list_recover', 'text'=>'恢复', 'plain'=>'true', 'icon'=>'fa-mail-reply'];
            $listButtonArr[] = ['id'=>'bt_list_hide', 'text'=>'屏蔽', 'plain'=>'true', 'icon'=>'fa-minus-circle'];
        }
        if (UserPower::checkUserPower('Read_Comment_Lock')) {
            $listButtonArr[] = ['id'=>'bt_list_lock', 'text'=>'锁定', 'plain'=>'true', 'icon'=>'fa-lock'];
            $listButtonArr[] = ['id'=>'bt_list_unlock', 'text'=>'解锁', 'plain'=>'true', 'icon'=>'fa-unlock'];
        }
        if (UserPower::checkUserPower('Read_Comment_Del')) {
            $listButtonArr[] = ['id'=>'bt_list_del', 'text'=>'删除', 'plain'=>'true', 'icon'=>'fa-trash'];
            $listButtonArr[] = ['id'=>'bt_list_forbid', 'text'=>'禁言', 'plain'=>'true', 'icon'=>'fa-ban'];
        }
        if (UserPower::checkUserPower('Read_Sensitive_Add')) {
            $listButtonArr[] = ['id'=>'bt_list_sensitive', 'text'=>'添加敏感词', 'plain'=>'true', 'icon'=>'fa-plus'];
        }
        if (UserPower::checkUserPower('Read_Comment_Waitpass')) {
            $listButtonArr[] = ['id' => 'bt_list_waitpass', 'text' => '加入待审池', 'plain' => 'true', 'icon' => 'fa-check'];
        }
//        if (UserPower::checkUserPower('Read_Comment_Edit')) {
//            $listButtonArr[] = ['id' => 'bt_list_pass', 'text' => '审核通过', 'plain' => 'true', 'icon' => 'fa-check'];
//        }
        return $this->view->setVars([
            'List'  => Template::createList('List', 'Read_Comment', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ]);
    }

    /**
     * 获取评论列表，倒序
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170420
     * modify by ck 20170912    添加评论人是否禁言状态
     * modify by ck 20180511
     * modify by ck 20180531    增加星级
     */
    public function getCommentAction()
    {
        $search = $this->request->getPost('search');
        $status = $this->request->getPost('status', 'int');
        $start = $this->request->getPost('start', 'string');
        $end = $this->request->getPost('end', 'string');
        $page = $this->request->getPost('page');
        $rows = $this->request->getPost('rows');
        $sort = $this->request->getPost('sort');
        $order = $this->request->getPost('order');
        $params = [
            'page' => $page - 1,
            'pageSize' => $rows
        ];
        if ($search['vague']) {
            $params['keyWord'] = $search['vague'];
        }
        if (is_numeric($status)) {
            $params['status'] = $status;
        }
        if ($start) {
            $params['startTime'] = strtotime($start) * 1000;
        }
        if ($end) {
            $params['endTime'] = strtotime($end) * 1000;
        }
        if ($sort) {
            $params['sort'] = $sort;
            $params['direction'] = $order;
        }
        try {
            $return = ['rows' => [], 'total' => 0];
            $schools = School::getPower();//学校权限
            if (!$schools) {
                return $this->sendDataGridError('无学校权限');
            } elseif ($schools !== true) {
                $params['schoolId'] = $schools;
            }

            $data = Read::getCommentList($params);
            if ($data && isset($data['totalCount']) && $data['totalCount'] != 0 && $data['data']) {
                $return['total'] = $data['totalCount'];
                foreach ($data['data'] as $datum) {
                    $datum['createtime'] = $datum['createtime'] ?
                        date('Y-m-d H:i:s', $datum['createtime'] / 1000) : '';
                    $datum['updatetime'] = $datum['updatetime'] ?
                        date('Y-m-d H:i:s', $datum['updatetime'] / 1000) : '';
                    $datum['status'] = $this->commentEnum['status'][$datum['status']];
                    $datum['star'] =
                        "<div class='comment-star' data-id='{$datum['id']}' data-star='{$datum['star']}'></div>";
                    $datum['username'] .= $datum['review'] == 2 ? ' <i class="fa fa-ban" style="color: red;"></i>' : '';
                    $return['rows'][] = $datum;
                }
            }
            return $this->sendJsonResponse($return);
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }

//        $status = $this->request->getPost('status', 'int');
//        $start  = $this->request->getPost('start', 'string');
//        $end    = $this->request->getPost('start', 'string');
//        $parameters = [
//            'columns'    => 'id,articletitle,comment,userid,username,createtime,status,teacherid,teachername,schoolid,schoolname,updatetime,locking,star',
//            'conditions' => 'status <> 2',
//            'order'      => 'id desc'
//        ];
//        if ($status !== null && $status !== '') {
//            $parameters['conditions']    .= ' AND status = :status:';
//            $parameters['bind']['status'] = $status;
//        }
//        if ($start) {
//            $parameters['conditions']   .= ' AND createtime >= :start:';
//            $parameters['bind']['start'] = $start;
//        }
//        if ($end) {
//            $parameters['conditions'] .= ' AND createtime <= :end:';
//            $parameters['bind']['end'] = $end;
//        }
//        $schools = School::getPower();
//        if (!$schools){
//            return $this->sendDataGridError('无学校权限');
//        }
//        else if ($schools !== true){
//            $parameters['conditions']   .= ' AND schoolid in ({idArr:array})';
//            $parameters['bind']['idArr'] = $schools;
//        }
//
//        //处理排序
//        $sort  = $this->request->getPost('sort', 'string');
//        $order = $this->request->getPost('order', 'string', 'asc');
//        if ($sort) {
//            $parameters['order'] = "{$sort} {$order}";
//        }
//
//        Main::runSearchVagueConditions($parameters['conditions'], ['articletitle', 'comment', 'username']);
////        $result = Main::runModelPaginator('\\Admin\\Models\\read\\Comment', $parameters, true);
//        $result = Main::runModelPage('\\Admin\\Models\\read\\Comment', $parameters, $this->commentEnum);
//
//        //添加学生状态
//        $userIds   = array_column($result['rows'], 'userid');
//        $userState = [];
//        if ($userIds) {
//            $userInfo = ReadUser::find([
//                'columns'    => 'userid,review',
//                'conditions' => 'userid in ({userId:array})',
//                'bind'       => ['userId' => $userIds]
//            ]);
//            $userInfo and $userState = array_column($userInfo->toArray(), 'review', 'userid');
//        }
//        foreach($result['rows'] as $index => &$row) {
////            $result['rows'][$index]['status'] = $row['status'] == 3 ? '屏蔽' : '正常';
////            $result['rows'][$index]['review'] = isset($userState[$row['userid']]) && $userState[$row['userid']] == 2
////                ? '<font style="color: red;">禁言</font>' : '<font style="color: #3c8b3c;">正常</font>';
//            if (isset($userState[$row['userid']]) && $userState[$row['userid']] == 2) {
//                $row['username'] .= ' <i class="fa fa-ban" style="color: red;"></i>';
//            }
//            $row['star'] = "<div class='comment-star' data-id='{$row['id']}' data-star='{$row['star']}'></div>";
//            $row['locking'] == 2 and $result['rows'][$index]['comment'] = '<i class="fa fa-lock" style="color: red;"></i> ' . $result['rows'][$index]['comment'];
//        }
//        unset($row);
//        return $this->response->setJsonContent($result);
    }

    /**
     * 屏蔽/删除评论
     *
     * @param  $type
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170420
     * modify by ck 20170601    添加状态，可恢复评论
     * modify by ck 20170807    记录屏蔽人信息
     * modify by ck 20170810    更改为http请求
     * modify by ck 20170912    更改返回结构
     * modify by ck 20180511    添加审核通过
     */
    public function setCommentStatusAction($type = null)
    {
        $ids = $this->request->getPost('ids', 'int');
        if (!$ids) {
            return $this->sendErrorResponse(400, '缺少必要参数');
        }
        switch ($type) {
            case 1:
                $actionType = 2;
                break;
            case 2:
                $actionType = 3;
                break;
            case 3:
                $actionType = 1;
                break;
            case 4:
                $actionType = 4;
                break;
            case 7:
                $actionType = 7;
                break;
            default:
                return $this->sendErrorResponse(400, '类型不正确');
        }
        $params = [
            'actionType' => $actionType,
            'commentIdList' => array_unique($ids),
            'operatorId' => (int)Main::getLoginUserInfo('userId'),
            'operatorName' => Main::getLoginUserInfo('userName')
        ];
        try {
            Read::setCommentManage($params);
            return $this->sendSuccessResponse('操作成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }


//        $ids = $this->request->getPost('ids', 'int');
//        if (!$ids) {
//            return $this->sendErrorResponse(400, '缺少必要参数');
//        }
//        $httpClient = new HttpClient(Main::getConfigByName(BaseRead::Service)['url']);
//        //转换类型...
//        switch ($type){
//            case 1: $actionType = 2; break;
//            case 2: $actionType = 3; break;
//            case 3: $actionType = 1; break;
//            case 4: $actionType = 4; break;
//            default: return $this->sendErrorResponse(400, '类型不正确');
//        }
//        $response   = $httpClient->postJson('/api/v1/comments/manage', [
//            'actionType'    => $actionType,
//            'commentIdList' => $ids,
//            'operatorId'    => intval(Main::getLoginUserInfo('userId')),
//            'operatorName'  => Main::getLoginUserInfo('userName')
//        ]);
//        Read::getResult($response);
////        if (!$response->isSuccess()){
////            return $this->sendErrorResponse(500, '操作失败', $response);
////        }
//        return $this->sendSuccessResponse('操作成功');

//        $this->view->disable();
//        $ids = $this->request->getPost('ids');
//        $ids or die('无数据！');
//        switch($type){
//            case 1: $result = $this->modelsManager->executeQuery("update \\Admin\\Models\\read\\Comment set status = :status: where id in ({idArr:array})",
//                ['status' => $type, 'idArr' => explode(',', $ids)]);
//                break;
//            case 2:
//            case 3: $result = $this->modelsManager->executeQuery("update \\Admin\\Models\\read\\Comment set status = :status:, teacherid = :teacherId:, teachername = :teacherName: where id in ({idArr:array})",
//                ['status' => $type, 'idArr' => explode(',', $ids), 'teacherId' => Main::getLoginUserInfo('userId'), 'teacherName' => Main::getLoginUserInfo('userName')]);
//                break;
//            default: die('类型不正确！');
//        }
//        Main::createCommitLog('read', 'comment', $type == 1 ? 'recover' : ($type == 3 ? 'hide' : 'del'), ['id' => $ids], null, '批量' . ($type == 1 ? '恢复' : ($type == 3 ? '屏蔽' : '删除')));
//        return $this->response->setContent(($type == 1 ? '恢复' : ($type == 3 ? '屏蔽' : '删除')) . ($result ? '成功' : '失败'));
    }

    /**
     * 操作单条评论状态
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180530
     */
    public function setSingleCommentStatusAction()
    {
        $id     = $this->request->getPost('id', 'int');
        $status = $this->request->getPost('status', 'int');
        if (!$id) {
            return $this->sendErrorResponse(400, '缺少id');
        }
        if (!$status) {
            return $this->sendErrorResponse(400, '缺少更改状态');
        }
        try {
            Read::setCommentStatus([$id], $status);
            switch ($status) {
                case 4:
                    $returnStatus['status'] = $this->commentEnum['status'][1];
                    break;
                case 5:
                    $returnStatus['status'] = $this->commentEnum['status'][4];
                    break;
                case 1:
                    $returnStatus['status'] = $this->commentEnum['status'][3];
                    break;
                case 7:
                    $returnStatus['status'] = $this->commentEnum['status'][7];
                    break;
            }
            $returnStatus['updatetime'] = date('Y-m-d H:i:s');
            return $this->sendJsonResponse($returnStatus);
//            return $this->sendJsonResponse(Read::getSingleComment($id), true);
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 设置星级
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180531
     */
    public function setSingleCommentStarAction()
    {
        $id   = $this->request->getPost('id', 'int');
        $star = $this->request->getPost('star', 'int');
        if (!$id) {
            return $this->sendErrorResponse(400, '缺少id');
        }
        if (!$star) {
            return $this->sendErrorResponse(400, '缺少星级');
        }
        try {
            Read::setCommentStar([$id], $star);
            return $this->sendSuccessResponse('标记成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

    /**
     * 锁定/解锁评论
     *
     * @param null $type
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170914
     */
    public function lockCommentAction($type = null)
    {
        $ids = $this->request->getPost('ids', 'int');
        if (!$ids) {
            return $this->sendErrorResponse(400, '缺少必要参数');
        }
        if (!in_array($type, [1, 2])) {
            return $this->sendErrorResponse(400, '操作类型不正确');
        }
        $httpClient = new HttpClient(Main::getConfigByName(BaseRead::Service)['url']);
        $response   = $httpClient->postJson('/api/v1/manage/articles/comments/locking', [
            'actionType'    => $type,
            'commentIdList' => $ids,
            'operatorId'    => intval(Main::getLoginUserInfo('userId')),
            'operatorName'  => Main::getLoginUserInfo('userName')
        ]);
        Read::getResult($response);
//        if (!$response->isSuccess()){
//            return $this->sendErrorResponse(500, '操作失败', $response);
//        }
        return $this->sendSuccessResponse(($type == 2 ? '锁定' : '解锁') . '成功');
    }

    /**
     * 设置学生禁言
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170912
     */
    public function forbidStudAction()
    {
        $studId     = array_unique($this->request->getPost('studId', 'int'));
        $forbidDay  = $this->request->getPost('forbidDay', 'int');
        if (!$forbidDay) {
            return $this->sendErrorResponse(400, '请填写正确的天数');
        }
        if (!$studId) {
            return $this->sendErrorResponse(400, '请选择评论后操作');
        }
        $httpClient = new HttpClient(Main::getConfigByName(BaseRead::Service)['url']);
        $response   = $httpClient->postJson('/api/v1/manage/forbid/comment', [
            'userIdList'    => $studId,
            'teacherId'     => intval(User::getId()),
            'forbidDay'     => intval($forbidDay)
        ]);
        Read::getResult($response);
//        if (!$response->isSuccess()) {
//            return $this->sendErrorResponse(500, '操作失败', $response);
//        }
        return $this->sendSuccessResponse('禁言成功');
    }

    /**
     * 删除文章下评论
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180112
     */
    public function delArticleCommentAction()
    {
        $id = $this->request->getPost('id', 'int');
        if (!$id) {
            return $this->sendErrorResponse(400, '缺少文章id');
        }
        try {
            $params = [$id];
            $userInfo = Main::getLoginUserInfo();
            $userArr = ['userId' => $userInfo['userId'], 'userName' => $userInfo['userName']];
            Read::delComment($userArr, $params);
            return $this->sendSuccessResponse('删除成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }

//        $id         = $this->request->getPost('id', 'int');
//        $all        = $this->request->getPost('all', 'string') == 'true';
//        $schoolIds  = $this->request->getPost('schoolIds', 'int');
//        if (!$id) {
//            return $this->sendErrorResponse(400, '缺少文章id');
//        }
//        if (!$all && !$schoolIds) {
//            return $this->sendErrorResponse(400, '缺少学校数据');
//        }
//        //查找目标数据下未删除评论id
//        $parameters = [
//            'columns'    => 'id',
//            'conditions' => 'status <> 2 and articleid = :id:',
//            'bind'       => ['id' => $id]
//        ];
//        if ($schoolIds) {
//            $parameters['conditions'] .= ' AND schoolid IN ({schoolIds:array})';
//            $parameters['bind']['schoolIds'] = $schoolIds;
//        }
//        $commentIds = Comment::find($parameters)->toArray();
//        if (!$commentIds) {
//            return $this->sendErrorResponse(400, '无需要删除评论');
//        }
//        $commentIds = array_column($commentIds, 'id');
//        $result = Comment::deleteRecordById(implode(",",$commentIds));
//        if (!$result) {
//            return $this->sendErrorResponse(400, '删除评论失败');
//        }
//        // 修改评论数
//        $parameters = [
//            'conditions' => "article_id = :id:",
//            'bind' => ['id' => $id]
//        ];
//        $comment_count = ArticleStatistics::findFirst($parameters);
//        if (!$comment_count) {
//            return $this->sendErrorResponse(400, '无需要删除评论！');
//        }
//        $comment_count->comment_count = 0;
//        if (!$comment_count->save()) {
//            return $this->sendErrorResponse(400, '修改评论数失败！');
//        }
//        return $this->sendSuccessResponse('删除评论成功!');
    }
//    public function delArticleCommentAction()
//    {
//        $id         = $this->request->getPost('id', 'int');
//        $all        = $this->request->getPost('all', 'string') == 'true';
//        $schoolIds  = $this->request->getPost('schoolIds', 'int');
//        if (!$id) {
//            return $this->sendErrorResponse(400, '缺少文章id');
//        }
//        if (!$all && !$schoolIds) {
//            return $this->sendErrorResponse(400, '缺少学校数据');
//        }
//        //查找目标数据下未删除评论id
//        $parameters = [
//            'columns'    => 'id',
//            'conditions' => 'status <> 2 and articleid = :id:',
//            'bind'       => ['id' => $id]
//        ];
//        if ($schoolIds) {
//            $parameters['conditions'] .= ' AND schoolid IN ({schoolIds:array})';
//            $parameters['bind']['schoolIds'] = $schoolIds;
//        }
//        $commentIds = Comment::find($parameters)->toArray();
//        if (!$commentIds) {
//            return $this->sendErrorResponse(400, '无需要删除评论');
//        }
//        $commentIds = array_column($commentIds, 'id');
//        $_POST = ['ids' => $commentIds];
//        return $this->delCommentAction(2);
//    }

    /**
     * 处理学段信息为中文展示
     *
     * @param $objArr
     * @param $field
     *
     * create by ck 20170503
     */
    private function dealLearnStages(&$objArr, $field)
    {
        foreach($objArr as $index => $obj){
            $learnStages = explode(',', $obj[$field]);
            $stagesName = [];
            foreach($learnStages as $stage){
                $stagesName[] = $this->stages[$stage];
            }
            $objArr[$index][$field] = implode(',', $stagesName);
        }
    }

    /**
     * 根据栏目ID及文章ID刷新Redis
     *
     * @param array $refreshData
     * @param integer|null $actionType
     * @return bool
     *
     * create by ck 20170509
     * modify by ck 20170519    结构更改
     * modify by ck 20170621    判断成功方式更改
     */
    private function refreshChannel($refreshData = [], $actionType = null)
    {
        $config = Main::getConfigByName(BaseRead::Service);
        $url = $config['url'];
        if(!$url) return false;
        $httpClient = (new HttpClient())->setBaseUrl($url);
        if(!$refreshData){
            $response = $httpClient->post('/api/v1/channels/refresh');
            Main::createCommitLog('read', 'article', 'refreshChannel', ['response' => $response],
                null, '刷新栏目' . ($response->isSuccess() ? '成功' : '失败'));
        }
        else{
            $channelIdArr = array_keys($refreshData);
            $channelIdArr = Channel::find([
                'columns'    => 'id,learnstages',
                'conditions' => 'status = 1 AND type = 1 AND id IN ({idArr:array})',
                'bind'       => ['idArr' => $channelIdArr]
            ])->toArray();
            $channelStage = array_column($channelIdArr, 'learnstages', 'id');
            //处理结构
            $requestData = ['actionType' => $actionType];
            foreach($refreshData as $channelId => $articleIds){
                $requestData['list'][] = ['channelId' => $channelId, 'articleList' => explode(',', $articleIds), 'learnStages' => $channelStage[$channelId]];
            }
//            $httpClient->setHeader('Content-Type', 'application/json');
            $response = $httpClient->postJson('/api/v1/articles/release', $requestData);
            Main::createCommitLog('read', 'article', 'refreshChannel', ['request' => $requestData, 'response' => $response, 'statusCode' => $response->header->statusCode],
                null, '刷新栏目文章' . ($response->isSuccess() ? '成功' : '失败'));
        }
        return $response->isSuccess();
    }

//    private function refreshComment($actionType = -1, $commentId = [])
//    {
//        $config = Main::getConfigByName(BaseRead::Service);
//        $url = $config['url'];
//        if(!$url) return false;
//        $httpClient = (new HttpClient())->setBaseUrl($url);
//        if(!$refreshData){
//            $response = $httpClient->postJson('/v1/commentnum/flush', ['actionType' => $actionType, '']);
//            $body     = $response->toObject();
//            Main::createCommitLog('read', 'article', 'refreshChannel', ['response' => $body],
//                null, '刷新栏目' . ($body->code == 2000 ? '成功' : '失败'));
//        }
//        else{
//            $channelIdArr = array_keys($refreshData);
//            $channelIdArr = Channel::find([
//                'columns'    => 'id,learnstages',
//                'conditions' => 'status = 1 AND type = 1 AND id IN ({idArr:array})',
//                'bind'       => ['idArr' => $channelIdArr]
//            ])->toArray();
//            $channelStage = array_column($channelIdArr, 'learnstages', 'id');
//            //处理结构
//            $requestData = ['actionType' => $actionType];
//            foreach($refreshData as $channelId => $articleIds){
//                $requestData['list'][] = ['channelId' => $channelId, 'articleList' => explode(',', $articleIds), 'learnStages' => $channelStage[$channelId]];
//            }
//            $httpClient->setHeader('Content-Type', 'application/json');
//            $response = $httpClient->postJson('/v1/articles/release', $requestData);
//            $body     = $response->toObject();
//            Main::createCommitLog('read', 'article', 'refreshChannel', ['request' => $requestData, 'response' => $body, 'statusCode' => $response->header->statusCode],
//                null, '刷新栏目文章' . ($body->code == 2000 ? '成功' : '失败'));
//        }
//        return $body->code == 2000;
//    }

    /**
     * 敏感词列表
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by ck 20180511
     */
    public function sensitiveAction()
    {
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition();
        Assets::easyUI('js/read/sensitive.js');
        if (!UserPower::checkUserPower('Read_Sensitive')) {
            return $this->sendViewError('无查看权限');
        }
        $listSearchArr = $listButtonArr = [];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_keyword', 'label' => '搜索：'];
        if (UserPower::checkUserPower('Read_Sensitive_Add')){
            $listButtonArr[] = ['id'=>'bt_list_add', 'text'=>'增加', 'icon'=>'fa-plus'];
        }
        if (UserPower::checkUserPower('Read_Sensitive_Del')){
            $listButtonArr[] = ['id'=>'bt_list_del', 'text'=>'删除', 'icon'=>'fa-trash'];
        }
        return $this->view->setVars([
            'List'          => Template::createList('List', 'Read_Sensitive', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ])
        ]);
    }

    /**
     * 获取敏感词列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180511
     */
    public function getSensitiveAction()
    {
        $page    = $this->request->getPost('page', 'int');
        $size    = $this->request->getPost('rows', 'int');
        $keyword = $this->request->getPost('keyword', 'string', '');
        return $this->sendJsonResponse(Read::getSensitive($page, $size, $keyword));
    }

    /**
     * 增加敏感词
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180511
     */
    public function addSensitiveAction()
    {
        $words = $this->request->getPost('words', 'string');
        if (!$words) {
            return $this->sendErrorResponse(400, '缺少敏感词');
        }
        if (!UserPower::checkUserPower('Read_Sensitive_Add')) {
            return $this->sendErrorResponse(400, '无操作权限');
        }
        Read::addSensitive($words);
        return $this->sendSuccessResponse('添加成功');
    }

    /**
     * 删除敏感词
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180511
     */
    public function delSensitiveAction()
    {
        $ids = $this->request->getPost('ids', 'int');
        if (!$ids) {
            return $this->sendErrorResponse(400, '缺少删除id');
        }
        if (!UserPower::checkUserPower('Read_Sensitive_Del')) {
            return $this->sendErrorResponse(400, '无操作权限');
        }
        Read::delSensitive($ids);
        return $this->sendSuccessResponse('删除成功');
    }

}

